package com.rosense.server.handle;

/**
 * @author 李岩飞
 * @email eliyanfei@126.com	
 * 2018年1月24日 上午11:27:15
 * 
 */
import java.util.Collection;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import com.rosense.client.i.IWriteReader;
import com.rosense.client.rpc.IRPCServer;
import com.rosense.client.rpc.RPCServerLinux;
import com.rosense.commons.reflect.ReflectUtils;
import com.rosense.server.config.HostCaches;
import com.rosense.server.config.HostConfigMgr;

/**
 * 启动监听器
 *
 * @author Storezhang
 */
@Service
public class StartupListener implements ApplicationListener<ContextRefreshedEvent> {

	@Override
	public void onApplicationEvent(ContextRefreshedEvent evt) {
		if (evt.getApplicationContext().getParent() == null) {
			ReflectUtils.createSharedReflections("classes", "bin");
			new Thread() {
				public void run() {
					try {
						HostConfigMgr.getConfig();
						System.out.println("startup rpc " + HostCaches.params.get("host") + ":" + HostCaches.params.get("port"));
						IRPCServer<?> server = new RPCServerLinux();
						server.bind("rpc", Integer.parseInt(HostCaches.params.get("port")), HostCaches.params.get("host"));
					} catch (Exception e) {
						e.printStackTrace();
					}
					final Collection<String> services = ReflectUtils.listSubClass(IWriteReader.class, "Mutiop");//
					for (String impl : services) {
						try {
							IWriteReader wr = (IWriteReader) Class.forName(impl).newInstance();
							HostCaches.wrMap.put(wr.getName(), wr);
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
					System.out.println("load listener:" + HostCaches.wrMap.size());
				}
			}.start();
		}

	}

}